package com.service.socket.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.dao.enums.KlineTypeEnum;
import com.service.dao.mapper.Kline1Mapper;
import com.service.dao.model.Kline1;
import com.service.dao.po.KlineVo;
import com.service.socket.service.Kline1Service;
import com.service.socket.service.KlineService;
import com.service.socket.service.KlineServiceFactory;
import com.service.utility.modelmapper.ModelMapperUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
//@DS("slave_1")
public class Kline1ServiceImpl extends ServiceImpl<Kline1Mapper, Kline1> implements Kline1Service, KlineService, InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        KlineServiceFactory.register(KlineTypeEnum.line_1, this);
    }

    @Override
    public KlineVo getByOpenTimeAndSymbol(Long openTime, String symbol) {
        Kline1 kline = getOne(new QueryWrapper<Kline1>().lambda()
                .eq(Kline1::getTimeOpen, openTime)
                .eq(Kline1::getSymbol, symbol).last("limit 1"));
        return ObjectUtils.isEmpty(kline) ? null : ModelMapperUtil.map(kline, KlineVo.class);
    }

    @Override
    public KlineVo getLastOneBySymbol(String symbol) {
        Kline1 kline = getOne(new QueryWrapper<Kline1>().lambda()
                .eq(Kline1::getSymbol, symbol).orderByDesc(Kline1::getTimeOpen).last("limit 1"));
        return ObjectUtils.isEmpty(kline) ? null : ModelMapperUtil.map(kline, KlineVo.class);
    }

    @Override
    public void updateKline(KlineVo klineVo) {
        saveOrUpdate(ModelMapperUtil.map(klineVo, Kline1.class));
    }

    @Override
    public List<KlineVo> listBySymbolAndLimit(String symbol, Long openTime, Integer limit) {
        return list(new QueryWrapper<Kline1>().lambda()
                .eq(Kline1::getSymbol, symbol)
                .le(Kline1::getTimeOpen, openTime)
                .orderByDesc(Kline1::getTimeOpen)
                .last("limit " + limit))
                .stream().map(item -> ModelMapperUtil.map(item, KlineVo.class))
                .collect(Collectors.toList());
    }
}
